package tools

import (
	"fmt"
	"gitee.com/jn-qq/similarity"
	"sync"
)

type simial struct {
	sim *similarity.Similar
	mut sync.Mutex
}

func (s *simial) TextSimilar(method similarity.SimilarMethod, txtList ...string) ([]float64, error) {
	var err error

	if len(txtList) < 2 {
		return nil, fmt.Errorf("参数错误,至少需要两段文本进行对比")
	}

	if s.sim == nil {
		s.mut.Lock()
		defer s.mut.Unlock()
		if s.sim == nil {
			// 初始化similar
			if s.sim, err = similarity.NewSimilar(); err != nil {
				return nil, err
			}
			// 加载停用词
			if err = s.sim.LoadStopWords("DEFAULT"); err != nil {
				return nil, err
			}
		}
	}
	var sourceList []float64
	for _, txt := range txtList[1:] {
		source, _ := s.sim.TextSimilarity(txtList[0], txt, method)
		sourceList = append(sourceList, source)
	}
	return sourceList, nil
}

var SIM = &simial{sim: nil, mut: sync.Mutex{}}
